export type $Task = { filePath: string; url: string; isDownload: boolean };
/**
 * 图片下载任务队列
 */
class DownLoadQueue {
  /** 任务队列 */
  public taskObj: Record<string, $Task | undefined> = {};

  /**
   * 下载保存文件
   */
  public async DownLoadSaveFile(task: $Task) {
    const that = this;
    // 判断是否已经下载过该图片
    if (await that.isExistFile(task.filePath)) {
      return;
    }
    if (task.filePath in that.taskObj && that.taskObj[task.filePath]?.isDownload) {
      return;
    }
    // 状态修改为正在下载
    task.isDownload = true;
    that.taskObj[task.filePath] = task;
    // 创建文件下载任务
    // #ifdef MP-WEIXIN
    uni.downloadFile({
      url: task.url,
      success: (res) => {
        if (res.statusCode === 200) {
          // 下载成功，保存文件
          uni.getFileSystemManager().saveFile({
            tempFilePath: res.tempFilePath,
            filePath: task.filePath,
            complete() {
              that.taskObj[task.filePath] = undefined;
            },
          });
        }
      },
    });
    // #endif

    // #ifdef APP-PLUS
    const downloadTask = plus.downloader.createDownload(task.url, { filename: task.filePath }, () => {
      that.taskObj[task.filePath] = undefined;
    });
    // 开始执行下载任务
    downloadTask.start();
    // #endif
  }
  /**
   * 根据文件路径判断文件是否存在
   * @param {string} filePath - 文件路径
   */
  public isExistFile(filePath: string): Promise<string | null> {
    return new Promise((resolve) => {
      // #ifdef APP-PLUS
      plus.io.resolveLocalFileSystemURL(
        filePath,
        () => resolve(filePath),
        () => resolve(null)
      );
      // #endif
      // #ifdef MP-WEIXIN
      uni.getFileSystemManager().readFile({
        filePath,
        success: () => {
          resolve(filePath);
        },
        fail: () => {
          resolve(null);
        },
      });
      // #endif
    });
  }
}

export const downLoadQueue = new DownLoadQueue();
